;(function(root, factory){
    if (typeof exports === "object") {
        // CommonJS
        module.exports = exports = factory();
    }
    else if (typeof define === "function" && define.amd) {
        // AMD
        define([], factory);
    }
    else {
        // Global (browser)
        root.RequestSender = factory();
    }
})(this, function(){
    const sdk = require('./sdk.js');
    const util = require('./Util.js');
    const URL = require('./URL.js');

    let sender = sdk.loadClass('HttpSender');
    let requestSender = {};
    function obj2QueryStr( o ){
        let queryStr = "";
        if (typeof o === 'string'){
            return o;
        }
        if (typeof o !== 'object'){
            return queryStr;
        }
        for (let k in o ){
            queryStr += "&" + k + "=" + o[k];
        }
        if (queryStr.length > 0){
            return queryStr.substring(1);
        }
        return queryStr;
    }
    function dataParser(rst){
        rst = JSON.parse(rst);
        // 失败
        if (rst.code == 0){
            throw rst.msg;
        }
        return rst.data;
    }
    // processData true转化为查询字符串
    requestSender.get = function(url, data, header){
        header = util.getOrDefault(header, {});
        data = util.getOrDefault(data, "");
        let query = obj2QueryStr(data);
        let _url = new URL(url);
        if (util.isEmpty(query) ) {
            if (!util.isEmpty(_url.search)){
                query = "&" + query;
            }
            else{
                query = "?" + query;
            }
            _url.search += query;
        }
        url = _url.toString();
        return dataParser(sender.get(url, obj2QueryStr(header)));
    }
    requestSender.post = function(url, data, processData, header){
        processData = util.getOrDefault(processData, false);
        header = util.getOrDefault(header, {});
        if (processData){
            data = obj2QueryStr(data);
        }
        else{
            data = JSON.stringify(data);
        }
        return dataParser(sender.post(url, obj2QueryStr(header), data));
    }
    requestSender.loadDoc = function(url, header){
        header = util.getOrDefault(header, {});
        let doc = sender.getDoc(url, obj2QueryStr(header));
        if (doc == "null" || doc === "null"){
            throw url + " not found";
        }
        return doc;
    }
    return requestSender;
})